/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfast.framework.orm.dataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.jfast.framework.kit.StrKit;
import com.jfast.framework.log.Logger;
import com.jfast.framework.orm.config.DataSourceConfig;

import javax.sql.DataSource;


/**
 * 默认Druid数据源 
 * @author zengjintao
 * @version 1.0
 * @createTime 2017年11月16日下午5:42:35
 */
public class DefaultDataSourceFactory extends AbstractDataSource {
	
	private static final Logger logger = Logger.getLogger(DefaultDataSourceFactory.class);
	private DruidDataSource dataSource;
	private String validationQuery = "select 1";
	
	public DefaultDataSourceFactory(DataSourceConfig dataSourceConfig) {
		super(dataSourceConfig);
	}

	@Override
	public DataSource getDataSource() {
		return dataSource;
	}

	@Override
	public void initDataSource(DataSourceConfig dataSourceConfig) {
		this.validationQuery = autoCheckValidationQuery(dataSourceConfig.getUrl());
		try {
			dataSource = new DruidDataSource();
			dataSource.setUrl(dataSourceConfig.getUrl());
			dataSource.setPassword(dataSourceConfig.getPassword());
			dataSource.setUsername(dataSourceConfig.getUsername());
			dataSource.setMaxActive(dataSourceConfig.getMaxActive());
			dataSource.setMinIdle(dataSourceConfig.getMinIdle());
			dataSource.setInitialSize(dataSourceConfig.getInitialSize());
			//让 druid 自动探测 driverClass值
			if(StrKit.isNotEmpty(dataSourceConfig.getDriverClassName())){
				dataSource.setDriverClassName(dataSourceConfig.getDriverClassName());
			}
		}catch (Exception e) {
			dataSource = null; 
			logger.error("DefaultDataSource loading error", e);
		}
	}
	
	/**
	 * @Title: autoCheckValidationQuery  
	 * @Description: 自动设定探测sql 
	 * @param url
	 * @return 
	 * @since V1.0.0
	 */
	private String  autoCheckValidationQuery(String url){
		if(url.startsWith("jdbc:oracle")){
			return "select 1 from dual";
		}else if(url.startsWith("jdbc:db2")){
			return "select 1 from sysibm.sysdummy1";
		}else if(url.startsWith("jdbc:hsqldb")){
			return "select 1 from INFORMATION_SCHEMA.SYSTEM_USERS";
		}else if(url.startsWith("jdbc:derby")){
			return "select 1 from INFORMATION_SCHEMA.SYSTEM_USERS";
		}
		return validationQuery;
	}
}
